package com.playball.lottery.nt;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import com.playball.lottery.util.AppUtils;
import com.playball.lottery.util.Logger;

public class GetJsonData {


	private static int connectTimeout = 60 * 1000;
	private static int readTimeout = 60 * 1000;
	
	//test local
//	static String host = "http://110.52.210.203:8022/";
//	static String api_host = "http://192.168.0.254:7777/";
	
	//test line
//	static String host = "http://110.52.210.203:8022/";
//	static String api_host = "http://110.52.210.203:8024/";


	//line
	static String host = "http://www.tcaio2o.com/";
	static String host_ip = "http://tcaio2o.com/";
	//static String api_host = "http://mobile.cp8848.cn/";
	static String api_host = "http://mobile.tcaio2o.com/";

	public static final String urlPath = api_host+"MobileHandler.ashx";
	public static final String urlPath_recharge ="http://www.tcaio2o.com/user/Recharge_Mobile.html?userid=";
	public static final String urlQRPath = host_ip+"user/register/wap/index.html?i=";
	
	public static final String zxPath = "http://zxapp.jiangduoduo.com/app/public/zx.html"; //资讯地址
	public static final String helpPath = "http://client.jiangduoduo.com/help/";
	public static Proxy mProxy = null;
	public static Context mContext;

	public static String cookies = null;
	public static List<String> cookies_strlist = null;
	public static List <Cookie>  cookies_list = null;
	private static final String staticJSBasePath = "http://static.jiangduoduo.com/";
	public static String getInputStreamByPost(Map<String, Object> params, Context context, boolean isold) throws Exception {
		mContext = context;
		// 拼接参数
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, Object> entry : params.entrySet()) {
			sb.append(entry.getKey()).append("=").append(entry.getValue().toString());
			sb.append("&");
		}
		String data = sb.deleteCharAt(sb.length() - 1).toString();
		Log.v("+++++++++++++",urlPath+"?"+data);
		// 检查网络
		detectProxy();
		// 发送请求
		HttpURLConnection conn = null;
		String strResponse = null;
		try {
			URL url;
			url = new URL(urlPath);
			// 打开连接
			if (mProxy != null) {
				conn = (HttpURLConnection) url.openConnection(mProxy);
			} else {
				conn = (HttpURLConnection) url.openConnection();
			}
			// 设置提交方式
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			// post方式不能使用缓存
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(true);
			byte[] requestStringBytes = data.getBytes("UTF-8");

			// 设置连接超时时间
			conn.setConnectTimeout(connectTimeout);
			conn.setReadTimeout(readTimeout);
			// 配置本次连接的Content-Type，配置为application/x-www-form-urlencoded
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			// 维持长连接
			conn.setRequestProperty("Connection", "Keep-Alive");
			// 设置浏览器编码
			conn.setRequestProperty("Charset", "UTF-8");
			if (cookies != null && cookies.length() > 0) {
				conn.setRequestProperty("Cookie", cookies);
			}
			// 开始连接
			conn.connect();

			OutputStream dos = conn.getOutputStream();
			// 将请求参数数据向服务器端发送
			dos.write(requestStringBytes);
			dos.flush();

			if (conn.getResponseCode() == 200) {
				// 获得服务器端输出流
				InputStream content = conn.getInputStream();
				strResponse = AppUtils.convertStreamToString(content);
//				System.out.println("response " + strResponse);
				// Get the cookie
				String cookie = conn.getHeaderField("set-cookie");
				if (cookie != null && cookie.length() > 0) {
					cookies = cookie;
				}
				
				// Get the cookie list
				Map<String, List<String>> cookiesMap = conn.getHeaderFields();
				for (Map.Entry<String, List<String>> entry : cookiesMap.entrySet()) {
					if("Set-Cookie".equals(entry.getKey())) {
						
//						Logger.e(entry.getKey(), "entry.getValue() = "+entry.getValue());
						
						cookies_strlist = entry.getValue();
						for(int i=0; i<cookies_strlist.size(); i++) {
							Logger.e(entry.getKey(), cookies_strlist.get(i));
						}
					}
				}
				
				
				mProxy = null;
				
//				Logger.e("cookies", cookies);
				
				return strResponse;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		return null;
	}

	// 通过输入流获得字节数组
	public static byte[] readStream(InputStream is) throws Exception {
		byte[] buffer = new byte[1024];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int len = 0;
		while ((len = is.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		is.close();
		return bos.toByteArray();
	}

	/**
	 * 获取网址内容
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String getContent(String url) throws Exception {
		StringBuilder sb = new StringBuilder();

		HttpClient client = new DefaultHttpClient();
		HttpParams httpParams = client.getParams();
		// 设置网络超时参数
		HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
		HttpConnectionParams.setSoTimeout(httpParams, 5000);
		HttpResponse response = client.execute(new HttpGet(url));
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			reader.close();
		}
		return sb.toString();
	}

	/**
	 * 获取网址内容
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String getContent(String url, boolean isNeedCompilePath) {
		if (true == isNeedCompilePath) {
			url = staticJSBasePath + url;
		}
		Log.d("", "GetJsonData.java->getContent url:" + url);
		try {
			StringBuilder sb = new StringBuilder();
			HttpClient client = new DefaultHttpClient();
			HttpParams httpParams = client.getParams();
			// 设置网络超时参数
			HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
			HttpConnectionParams.setSoTimeout(httpParams, 30000);
			HttpResponse response = client.execute(new HttpGet(url));
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 1024);

				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				reader.close();
			}
			return sb.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 检查代理，是否cnwap接入
	 */
	private static void detectProxy() {
		ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni != null && ni.isAvailable() && ni.getType() == ConnectivityManager.TYPE_MOBILE) {
			String proxyHost = android.net.Proxy.getDefaultHost();
			int port = android.net.Proxy.getDefaultPort();
			if (proxyHost != null) {
				final InetSocketAddress sa = new InetSocketAddress(proxyHost, port);
				mProxy = new Proxy(Proxy.Type.HTTP, sa);
			}
		}
	}
	
	/**
	 * 同步一下cookie
	 */
	public static void synCookies(Context context, String url, boolean isLogin) {
		CookieSyncManager.createInstance(context);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);
		cookieManager.removeSessionCookie(); //移除
		
		if(cookies_strlist != null) {
			//cookies是在Http连接中获得的cookie
			if(isLogin) {
				for(int i=0; i<cookies_strlist.size(); i++) {
					cookieManager.setCookie(url, cookies_strlist.get(i)); 
					CookieSyncManager.getInstance().sync();
				}
			} else {
				for(int i=0; i<cookies_strlist.size(); i++) {
					
					String cookies_tmp = cookies_strlist.get(i);
//					Logger.e("cookies_strlist.get("+i+")", cookies_tmp);
					
					int start = cookies_tmp.indexOf("expires=");
					if(start > 0) {
						int end = cookies_tmp.indexOf(";", start + 1);
						if(end > start) {
							cookies_tmp = cookies_tmp.substring(0, start) + "expires=Fri, 10-Aug-1900 09:18:39 GMT" + cookies_tmp.substring(end);
						}
					}
//					Logger.e("cookies_tmp", cookies_tmp);
					cookieManager.setCookie(url, cookies_tmp); 
					CookieSyncManager.getInstance().sync();
				}
			}
		}
	}
	
	
	
	/**
	 * 以post方式发送请求，访问web
	 * 
	 * @param uri
	 *            web地址
	 * @return 响应数据
	 */
	public static String getInputStreamByPost2(Map<String, Object> params, Context context, boolean isold) {
		// 检查网络
		mContext = context;
		detectProxy();
		
		// 初始化
		BufferedReader reader = null;
		StringBuffer sb = null;
		HttpClient client = new DefaultHttpClient();
		HttpPost request = new HttpPost(urlPath);

		// 保存要传递的参数
		List<NameValuePair> params_list = new ArrayList<NameValuePair>();
		// 添加参数
		for (Map.Entry<String, Object> entry : params.entrySet()) {
			params_list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
		}

		try {
			// 设置字符集
			HttpEntity entity = new UrlEncodedFormEntity(params_list, "utf-8");
			// 请求对象
			request.setEntity(entity);
			
			// 设置保存cookies
			HttpContext hctx = new BasicHttpContext();
		    CookieStore cookieStore = new BasicCookieStore();
		    hctx.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			
			// 发送请求
			HttpResponse response = client.execute(request, hctx);
			// 请求成功
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				
				//读取cookies
				cookies_list = cookieStore.getCookies();
				
				
				reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				sb = new StringBuffer();
				String line = "";
				while ((line = reader.readLine()) != null) {
					sb.append(line+"\r\n");
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流
				if (null != reader) {
					reader.close();
					reader = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (null != sb) {
			return sb.toString();
		}
		return null;
	}
	
	/**
	 * 同步cookies
	 * @param context
	 * @param url
	 */
	public static void synCookies2(Context context, String url) {
		if(cookies_list == null) return;
		
		if (!cookies_list.isEmpty()){  
		    CookieSyncManager.createInstance(context);  
		    CookieManager cookieManager = CookieManager.getInstance();  
		    for (Cookie cookie : cookies_list){  
		        String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();  
		        cookieManager.setCookie(url, cookieString);  
		        CookieSyncManager.getInstance().sync();  
		    }  
		}
	}

}
